﻿/* Copyright (c) 2010 EPiServer AB
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
 * documentation files (the "Software"), to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
 * to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
 * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using EPiServer.Core;
using EPiServer.Core.Html;
using EPiServer.Filters;
using EPiServer.Municipality.Configuration;
using Constants=EPiServer.Municipality.Configuration.Constants;

namespace EPiServer.Municipality.Templates.Pages {
    public partial class Search : TemplatePage {
        /* *******************************************************************
         * Properties
         * *******************************************************************/
        #region protected string SearchPageLink
        /// <summary>
        /// Gets the SearchPageLink of the QuickSearch
        /// </summary>
        /// <value></value>
        protected string SearchPageLink {
            get {
                if (IsValue(Constants.DynamicSearchpagePropertyName)) {
                    return GetPage((PageReference)CurrentPage[Constants.DynamicSearchpagePropertyName]).LinkURL;
                }
                return string.Empty;
            }
        }
        #endregion
        #region protected string SearchQuery
        /// <summary>
        /// Gets the SearchQuery of the Search
        /// </summary>
        /// <value></value>
        protected string SearchQuery {
            get {
                if (Request["query"] == null)
                    return String.Empty;

                string quickSearchText = Translate("/municipality/units/quicksearch/searchlabel");
                if (Request["query"] == quickSearchText)
                    return String.Empty;
                
                return Request["query"];
            }
        }
        #endregion
        /* *******************************************************************
         * Methods
         * *******************************************************************/
        #region override protected void OnInit(EventArgs e)
        override protected void OnInit(EventArgs e) {
            InitializeComponent();
            base.OnInit(e);
        }
        #endregion
        #region private void InitializeComponent()
        /// <summary>
        /// 
        /// </summary>
        private void InitializeComponent() {
            Load += Page_Load;
            SearchDataSourceCtrl.Filter += PageSearch_Filter;
            ContactSearchDataSourceCtrl.Filter += ContactSearch_Filter;
        }
        #endregion
        #region protected string GetDescription(object dataItem)
        /// <summary>
        /// 
        /// </summary>
        /// <param name="dataItem"></param>
        /// <returns></returns>
        protected string GetDescription(object dataItem) {
            var page = dataItem as PageData;

            if (page == null) {
                return string.Empty;
            }

            var previewText = String.Empty;

            if (page.Property["ListIntro"] != null && page.Property["ListIntro"].ToString().Length > 0) {
                previewText = page.Property["ListIntro"].ToWebString();
            } else if (page.Property["MainBody"] != null) {
                previewText = page.Property["MainBody"].ToWebString();
            }

            return string.IsNullOrEmpty(previewText) ? previewText : string.Format("<p>{0}</p>", TextIndexer.StripHtml(previewText, 255));
        }
        #endregion
        #region private void ExcecuteSearch(string query)
        /// <summary>
        /// 
        /// </summary>
        /// <param name="query"></param>
        private void ExcecuteSearch(string query) {
            SearchDataSourceCtrl.SearchQuery = query;
            SearchDataSourceCtrl.LanguageBranches = CurrentPage.LanguageBranch;
            SearchDataSourceCtrl.DataBind();
            SearchResult.DataBind();

            ContactSearchDataSourceCtrl.SearchQuery = query;
            ContactSearchDataSourceCtrl.LanguageBranches = CurrentPage.LanguageBranch;
            ContactSearchDataSourceCtrl.DataBind();
            ContactsSearchResult.DataBind();
        }
        #endregion
        /* *******************************************************************
         *  Event methods 
         * *******************************************************************/
        #region protected void Page_Load(object sender, EventArgs e)
        /// <summary>
        /// This method is called when the Page's Load event has been fired.
        /// </summary>
        /// <param name="sender">The <see cref="object"/> that fired the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> of the event.</param>
        protected void Page_Load(object sender, EventArgs e) {
            ((MasterPages.Default)Master).CssClass = "searchpage";
            ExcecuteSearch(SearchQuery);

            if (SearchResult.Items.Count == 0)
                SearchResult.Visible = false;
            if (ContactsSearchResult.Items.Count == 0)
                ContactsSearchResult.Visible = false;

            if (String.IsNullOrEmpty(SearchQuery)) {
                SearchMessage.Text = "<div class=\"systeminfo\"><div>" + Translate("/municipality/templates/search/nosearch") + "</div></div>";
            } else if (SearchResult.Items.Count == 0 && ContactsSearchResult.Items.Count > 0) {
                SearchMessage.Text = "<div class=\"systeminfo\"><div>" + String.Format(Translate("/municipality/templates/search/emptypagesearch"), "<strong>" + SearchQuery + "</strong>", ContactsSearchResult.Items.Count) + "</div></div>";
            } else if (SearchResult.Items.Count == 0 && ContactsSearchResult.Items.Count == 0) {
                SearchMessage.Text = "<div class=\"systeminfo\"><div>" + String.Format(Translate("/municipality/templates/search/emptysearch"), "<strong>" + SearchQuery + "</strong>") + "</div></div>";
            }
        }
        #endregion
        #region private void PageSearch_Filter(object sender, FilterEventArgs e)
        /// <summary>
        /// </summary>
        /// <param name="sender">The <see cref="object"/> that fired the event.</param>
        /// <param name="e">The <see cref="FilterEventArgs"/> of the event.</param>
        private void PageSearch_Filter(object sender, FilterEventArgs e) {
            for (var i = 0; i < e.Pages.Count; i++) {
                if(e.Pages[i].PageTypeID == SiteSettings.Instance.ContactPageTypeId) {
                    e.Pages.RemoveAt(i);
                    i--;    
                }
            }
        }
        #endregion
        #region private void ContactSearch_Filter(object sender, FilterEventArgs e)
        /// <summary>
        /// </summary>
        /// <param name="sender">The <see cref="object"/> that fired the event.</param>
        /// <param name="e">The <see cref="FilterEventArgs"/> of the event.</param>
        private void ContactSearch_Filter(object sender, FilterEventArgs e) {
            for (var i = 0; i < e.Pages.Count; i++) {
                if (e.Pages[i].PageTypeID != SiteSettings.Instance.ContactPageTypeId) {
                    e.Pages.RemoveAt(i);
                    i--;
                }
            }
        }
        #endregion
    }
}
